package com.zhang.zhangapp.view.mine;

import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.makeramen.roundedimageview.RoundedImageView;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.CalendarMode;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.zhang.zhangapp.LoginActivity;
import com.zhang.zhangapp.R;
import com.zhang.zhangapp.application.MApplication;
import com.zhang.zhangapp.base.Constant;
import com.zhang.zhangapp.base.config.BaseConfig;
import com.zhang.zhangapp.base.config.HttpConfig;
import com.zhang.zhangapp.base.http.MCallback;
import com.zhang.zhangapp.bean.TokenData;
import com.zhang.zhangapp.bean.user.User;
import com.zhang.zhangapp.http.CommonHttp;
import com.zhang.zhangapp.http.UpLoadHttp;
import com.zhang.zhangapp.utils.DateUtil;
import com.zhang.zhangapp.utils.PicassoImageLoader;
import com.zhang.zhangapp.utils.SPUtils;
import com.zhang.zhangapp.utils.T;
import com.zhang.zhangapp.utils.enums.DateStyle;
import com.zhang.zhangapp.view.BaseAppCompatActivityActivity;
import com.zhang.zhangapp.view.custom.EditDialog;
import com.zhang.zhangapp.view.custom.SexDialog;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 罗肖 on 2018/3/28.
 */

@ContentView(R.layout.activity_myself_info)
public class MineInfoActiviy extends BaseAppCompatActivityActivity {

    public final static int RIMAGE_PICKER = 10005;

    @ViewInject(R.id.myself_info_user_image)
    ImageView mineImage;
    @ViewInject(R.id.myself_login_pwd)
    TextView loginPwdText;
    @ViewInject(R.id.myself_nickname)
    TextView nickNameText;
    @ViewInject(R.id.myself_pay_pwd)
    TextView payPwdText;
    @ViewInject(R.id.myself_phone_no)
    TextView phoneNoText;
    @ViewInject(R.id.myself_sex)
    TextView sexText;
    @ViewInject(R.id.myself_brithday)
    TextView brithdayText;


    private User user;

    ImageOptions imageOptions;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        initImagePicker();
        initImageOptions();

    }
    public void initImageOptions() {
        imageOptions = new ImageOptions.Builder()
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setRadius(DensityUtil.dip2px(100))
                .setCrop(true)//是否对图片进行裁剪
                .setFailureDrawableId(R.mipmap.header_default)
                .setLoadingDrawableId(R.mipmap.header_default)
                .build();
    }

    private void initView() {
        user = MApplication.getInstance().getUser();
        x.image().bind(mineImage, HttpConfig.IMAGE_HTTP_PATH + user.getPhoto(), imageOptions);
        loginPwdText.setText(user.getLoginsec());
        nickNameText.setText(user.getNickname());
        payPwdText.setText(user.getPaysec());
        phoneNoText.setText(user.getMobilenum());
        sexText.setText(user.getSex());
        brithdayText.setText(user.getBrithday());
        if (user.getPaysec() != null && !user.getPaysec().equals("")) {
            payPwdText.setText("修改支付密码");
        }
        if (user.getLoginsec() != null && !user.getLoginsec().equals("")) {
            loginPwdText.setText("修改登录密码");
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        initView();
    }

    @Event(type = View.OnClickListener.class, value = {R.id.myself_info_user_image, R.id.myself_login_pwd, R.id.myself_nickname,
            R.id.myself_pay_pwd, R.id.myself_phone_no, R.id.myself_sex, R.id.action_bar_left_image, R.id.myself_brithday})
    private void onClick(View view) {
        switch (view.getId()) {
            case R.id.myself_info_user_image:
                openSelectPhoto();
                break;
            case R.id.myself_login_pwd:
                openSettingPwdActivity("登录密码", Constant.设置登录密码验证码);
                break;
            case R.id.myself_nickname:
                setNickNameText();
                break;
            case R.id.myself_pay_pwd:
                openSettingPwdActivity("支付密码", Constant.设置支付密码);
                break;
            case R.id.myself_phone_no:
                break;
            case R.id.myself_sex:
                updateSex();
                break;
            case R.id.myself_brithday:
                setBrithdayText();
                break;
            case R.id.action_bar_left_image:
                this.finish();
                break;
        }
    }

    private void setBrithdayText() {
        final SimpleCalendarDialogFragment dialogFragment = new SimpleCalendarDialogFragment();
        dialogFragment.show(getSupportFragmentManager(), "选择日期");
        dialogFragment.setOnCalenderClick(new CalendarClick() {
            @Override
            public void onCalendarClick(CalendarDay date) {
                brithdayText.setText(DateUtil.DateToString(date.getDate(), DateStyle.YYYY_MM_DD));
                updateMember("brithday", DateUtil.DateToString(date.getDate(), DateStyle.YYYY_MM_DD));
                dialogFragment.dismiss();
            }
        });
    }

    private void updateSex() {
        final SexDialog dialog = new SexDialog(this);
        dialog.show();
        dialog.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                TextView textView = (TextView) v;
                sexText.setText(textView.getText().toString());
                updateMember("sex", textView.getText().toString());
                dialog.dismiss();
            }
        });
    }

    private void openSettingPwdActivity(String title, String type) {
        Intent intent = new Intent(this, SetPwdActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    /**
     * update nickname
     */
    private void setNickNameText() {
        final EditDialog dialog = new EditDialog(this, "修改昵称",MApplication.getInstance().getUser().getNickname());
        dialog.show();
        dialog.setOnSureClickListenrer(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog.getText().isEmpty()) {
                    T.showShort(MineInfoActiviy.this, "请填写昵称");
                    return;
                }
                nickNameText.setText(dialog.getText());
                updateMember("nickname", dialog.getText());
                dialog.dismiss();
            }
        });
    }

    public void updateMember(String key, String value) {
        if (MineInfoActiviy.this.showLoadingDialog()) {
            Map<String, String> params = new HashMap<>();
            params.put("memberId", user.getMemberId());
            params.put("nickname", user.getNickname());
            params.put("photo", user.getPhoto());
            params.put("name", user.getName());
            params.put("sex", user.getSex());
            params.put("brithday", user.getBrithday());
            params.put(key, value);

            CommonHttp.commonHttp("hzg/member/updateMember", params, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    try {
                        Gson gson = new Gson();
                        User user = gson.fromJson(data, User.class);
                        if (user != null) {
                            MineInfoActiviy.this.user = user;
                            MApplication.getInstance().setUser(user);
                        }
                    } catch (Exception e) {
                        T.showShort(MineInfoActiviy.this, "请求失败");
                    }
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    T.showShort(MineInfoActiviy.this, ex.getMessage());
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {
                    T.showShort(MineInfoActiviy.this, cex.getMessage());
                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(1);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.CIRCLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    private void openSelectPhoto() {
        Intent intent = new Intent(this, ImageGridActivity.class);
        startActivityForResult(intent, RIMAGE_PICKER);
    }

    private void upLoadMineImage(String imagePath) {
        if (showLoadingDialog()) {
            UpLoadHttp.upLoadFile(imagePath, new MCallback() {
                @Override
                public void onSuccess(String data) {
                    x.image().bind(mineImage, HttpConfig.IMAGE_HTTP_PATH + data, MApplication.getInstance().getImageOptions());
                    updateMember("photo", data);
                }

                @Override
                public void onSuccess(String message, String code) {

                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dismisionDalog();
                }
            });
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {
                case RIMAGE_PICKER:
                    List<ImageItem> itemList = (ArrayList<ImageItem>) data.getSerializableExtra("extra_result_items");
                    if (itemList != null) {
                        //  mineImage.setImageURI(Uri.parse(itemList.get(0).path));
                        //  x.image().bind(mineImage,itemList.get(0).path,MApplication.getInstance().getImageOptions());
                        upLoadMineImage(itemList.get(0).path);
                    }
                    break;
            }
        }
    }

    public interface CalendarClick {
        void onCalendarClick(CalendarDay date);
    }

    public static class SimpleCalendarDialogFragment extends AppCompatDialogFragment implements OnDateSelectedListener {

        private TextView textView;
        private CalendarClick oncalenderClick;

        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            LayoutInflater inflater = getActivity().getLayoutInflater();

            //inflate custom layout and get views
            //pass null as parent view because will be in dialog layout
            View view = inflater.inflate(R.layout.calendar_dialog, null);
            MaterialCalendarView widget = (MaterialCalendarView) view.findViewById(R.id.calendarView);
            widget.setOnDateChangedListener(this);
            widget.state().edit()
                    .setCalendarDisplayMode(CalendarMode.MONTHS)
                    .commit();

            return new AlertDialog.Builder(getActivity())
                    .setTitle("选择日期")
                    .setView(view)
                    .create();
        }

        public void setOnCalenderClick(CalendarClick calendarClick) {
            this.oncalenderClick = calendarClick;
        }

        @Override
        public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
            if (oncalenderClick != null)
                oncalenderClick.onCalendarClick(date);
        }
    }
}
